﻿
using AutoMapper;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Routing.Template;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Operations;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Internal;
using Microsoft.VisualBasic;
using System.Data;
using System.Reflection;
using WidgetsDesign.API.DataBase;
using WidgetsDesign.API.Dtos;
using WidgetsDesign.API.Models;
using WidgetsDesign.API.Services;
using static Microsoft.EntityFrameworkCore.DbLoggerCategory;
using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Pdf;
using System.IO;
using Org.BouncyCastle.Utilities.Zlib;
using Spire.Doc.Fields;
using Aspose.Words;
using Document = Spire.Doc.Document;
using Section = Spire.Doc.Section;
using Paragraph = Spire.Doc.Documents.Paragraph;
using Bookmark = Aspose.Words.Bookmark;
using PdfSharp.Charting;
using DocumentObject = Spire.Doc.DocumentObject;
using Microsoft.AspNetCore.Hosting;
using Newtonsoft.Json;


// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860

namespace WidgetsDesign.API.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class CraneOperationController : ControllerBase
    {
        private readonly ICraneOperationRepository _craneOperationRepository;
        private readonly IMapper _Mapper;
        private readonly AppDbContext _context;
        private readonly IWebHostEnvironment _webHostEnvironment;
        public CraneOperationController(IWebHostEnvironment webHostEnvironment, ICraneOperationRepository craneOperationRepository, IMapper mapper, AppDbContext context)
        {
            _craneOperationRepository = craneOperationRepository;
            _Mapper = mapper;
            _context = context;
            _webHostEnvironment = webHostEnvironment;
        }
        /// <summary>
        /// word转pdf
        /// </summary>
        /// <param name="craneOperationToPdf"></param>
        /// <returns></returns>



        [HttpPost]
        public async Task<IActionResult> OperationToPdf(string Id)
        {

            var craneOperation = await _context.craneoperation.FirstOrDefaultAsync(co => co.Id == Id);
            var saveName = @"Pdf\新版吊装作业许可" + Id + ".pdf";
            string web_path = _webHostEnvironment.WebRootPath;
            string folderPath = Path.Combine("wwwroot");

            if (!Directory.Exists(folderPath))
            {
                Directory.CreateDirectory(folderPath);
            }
            string path = Path.Combine(folderPath, saveName);
            string inpath = Path.Combine(folderPath, @"wordmodel\新版吊装作业许可.doc");
            string inputFilePath = inpath;// 替换为你的Word文档路径  
            string outputFilePath = path;

            if (craneOperation == null)
            {
                // 如果没有找到记录，返回错误信息  
                return Ok(new { code = 200, ret = false, data = "", message = "未找到对应的吊装作业记录" });
            }
            else
            {
                //加载Word文档  
                //新写一个函数用于书签对应值插入if (bookmarkName == "YourSpecificBookmarkName")  {rturn }
                string last = _craneOperationRepository.CraneOperationTopdf(inputFilePath, outputFilePath, craneOperation);
                return Ok(new { code = 200, ret = true, data = saveName, message = "创建成功" + outputFilePath });

            }

        }
        [HttpPost]
        public async Task<IActionResult> CreateCraneOperation([FromBody] CraneOperationModel craneOperationModel)
        {
            if (String.IsNullOrEmpty(craneOperationModel.Id))
            {
                craneOperationModel.Id = Guid.NewGuid().ToString();
                craneOperationModel.State = "1";
                _craneOperationRepository.CreateCraneOperation(craneOperationModel);
                await _craneOperationRepository.SaveAsync();
                return Ok(new { code = 200, ret = true, data = craneOperationModel, message = "创建成功" });
            }
            else
            {
                var query = from d in _context.craneoperation
                            where d.Id == craneOperationModel.Id
                            select d;
                var item = await query.FirstOrDefaultAsync();
                if (item != null)
                {
                    item.NoNumber = craneOperationModel.NoNumber;
                    item.ApplicantCompany = craneOperationModel.ApplicantCompany;
                    item.ApplyTime = craneOperationModel.ApplyTime;
                    item.HomeworkAreaManagementUnit = craneOperationModel.HomeworkAreaManagementUnit;
                    item.TerritorySupervisor = craneOperationModel.TerritorySupervisor;
                    item.Proposer = craneOperationModel.Proposer;
                    item.Guardian = craneOperationModel.Guardian;
                    item.WorkLocation = craneOperationModel.WorkLocation;
                    item.JobContent = craneOperationModel.JobContent;
                    item.JobContent1 = craneOperationModel.JobContent1;
                    item.Operator = craneOperationModel.Operator;
                    item.AssociationOn = craneOperationModel.AssociationOn;
                    item.LiftingCertificate = craneOperationModel.LiftingCertificate;
                    item.CraneCertificate = craneOperationModel.CraneCertificate;
                    item.StartMachineryName = craneOperationModel.StartMachineryName;
                    item.LiftingObjectContent = craneOperationModel.LiftingObjectContent;
                    item.LiftingObjectMass = craneOperationModel.LiftingObjectMass;
                    item.JobGrade = craneOperationModel.JobGrade;
                    item.IsPlanCompiled = craneOperationModel.IsPlanCompiled;
                    item.StartTime = craneOperationModel.StartTime;
                    item.EndTime = craneOperationModel.EndTime;
                    item.ExistingRisk = craneOperationModel.ExistingRisk;
                    if (!string.IsNullOrEmpty(craneOperationModel.SafetyPrecautions))
                    {
                        item.SafetyPrecautions = craneOperationModel.SafetyPrecautions;
                    }
                    if (!string.IsNullOrEmpty(craneOperationModel.Organizer))
                    {
                        item.Organizer = craneOperationModel.Organizer;
                    }
                    if (!string.IsNullOrEmpty(craneOperationModel.ScheduleId))
                    {
                        item.ScheduleId = craneOperationModel.ScheduleId;
                    }
                    if (!string.IsNullOrEmpty(craneOperationModel.ScheduleContent))
                    {
                        item.ScheduleContent = craneOperationModel.ScheduleContent;
                    }
                }
                await _context.SaveChangesAsync();
                return Ok(new { ret = true, data = item, code = 200 });
            }
        }
        [HttpPost]
        public async Task<IActionResult> CreateCraneOperationRisk([FromBody] CraneOperationModel craneOperationModel)
        {
            _craneOperationRepository.CreateCraneOperationRisk(craneOperationModel);
            craneOperationModel.State = "2";
            await _craneOperationRepository.SaveAsync(); return Ok(new { code = 200, data = "", ret = true });
        }
        /// <summary>
        /// 吊装作业许可签字部分
        /// </summary>
        /// <param name="craneOperationModel"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> CreateCraneOperationSign([FromBody] CraneOperationModel craneOperationModel)
        {
            _craneOperationRepository.CreateCraneOperationSign(craneOperationModel);
            craneOperationModel.State = "3";
            await _craneOperationRepository.SaveAsync(); return Ok(new { code = 200, data = "", ret = true });
        }

        [HttpPost]
        public async Task<IActionResult> CreateCraneOperationClose([FromBody] CraneOperationModel craneOperationModel)
        {
            var query = from d in _context.craneoperation
                        where d.Id == craneOperationModel.Id
                        select d;
            var item = await query.FirstOrDefaultAsync();
            if (item != null && !String.IsNullOrEmpty(craneOperationModel.CancelorClose))
            {
                CancelorClose safeDataList = JsonConvert.DeserializeObject<CancelorClose>(craneOperationModel.CancelorClose);
                if (safeDataList.endtype == "1")
                {
                    item.State = "7";
                }
                if (safeDataList.endtype == "2")
                {
                    item.State = "6";
                }
                if (safeDataList.endtype == "3")
                {
                    item.State = "5";
                }
                item.CancelorClose = craneOperationModel.CancelorClose;
                await _context.SaveChangesAsync();
            }
            return Ok(new { ret = true, data = item, code = 200 });
        }
        public class CancelorClose
        {
            public string endtype { get; set; }
            public DateTime? endtime { get; set; }
            public string sqr { get; set; }
            public string pzr { get; set; }
        }
        class CraneOperationData
        {
            public string Id { get; set; }
            public DateTime? ApplyTime { get; set; }
            public string? WorkLocation { get; set; }
            public DateTime? EndTime { get; set; }
            public string? State { get; set; }
            public string? JobContent { get; set; }
            public string? ApplicantCompany { get; set; }
            public string? Proposer { get; set; }

        }
        [HttpGet]
        public async Task<IActionResult> QueryCraneOperationList([FromQuery] int pageIndex, int pageSize, DateTime? startTime, DateTime? endTime)
        {

            var query = _context.craneoperation.Select(h => new CraneOperationData
            {
                Id = h.Id,
                ApplyTime = h.ApplyTime,
                WorkLocation = h.WorkLocation,
                EndTime = h.EndTime,
                State = h.State,
                JobContent = h.JobContent,
                ApplicantCompany = h.ApplicantCompany,
                Proposer = h.Proposer
            });
            if (startTime.HasValue)
            {
                query = query.Where(h => h.ApplyTime >= startTime);
            }

            if (endTime.HasValue)
            {
                query = query.Where(h => h.ApplyTime <= endTime);
            }
            var total = await query.CountAsync();
            query = query.OrderByDescending(h => h.ApplyTime);
            query = query.Skip(pageSize * (pageIndex - 1))
                     .Take(pageSize);
            var list = await query.ToListAsync();
            for (int i = 0; i < list.Count; i++)
            {
                if (int.Parse(list[i].State) <= 4)
                {
                    if (list[i].EndTime <= DateTime.Now)
                    {
                        list[i].State = "7";
                    }
                }
            }
            return Ok(new { ret = true, data = list, code = 200, total });
        }
        [HttpGet]
        public async Task<IActionResult> QueryCraneOperationById([FromQuery] string id)
        {
            var query = from d in _context.craneoperation
                        where d.Id == id
                        select d;
            var item = await query.FirstOrDefaultAsync();
            return Ok(new { ret = true, data = item, code = 200 });
        }

        [HttpGet]
        public IActionResult DeleteCraneOperation([FromQuery] string id)
        {
            var query = from d in _context.craneoperation where d.Id == id select d;
            _context.craneoperation.RemoveRange(query);
            _context.SaveChanges();
            return Ok(new { ret = true, data = new { }, code = 200 });
        }
        /// <summary>
        /// 选择附表
        /// </summary>
        /// <param name="craneOperationModel"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> CreateCraneOperationSchedule([FromBody] CraneOperationModel craneOperationModel)
        {
            var query = from d in _context.craneoperation
                        where d.Id == craneOperationModel.Id
                        select d;
            var item = await query.FirstOrDefaultAsync();
            if (item != null)
            {
                //判断当前传入的ScheduleId不为空
                if (!String.IsNullOrEmpty(craneOperationModel.ScheduleId))
                {   //判断当前ScheduleId和数据库ScheduleId是否一致
                    if (item.ScheduleId != craneOperationModel.ScheduleId)
                    {
                        item.ScheduleId = craneOperationModel.ScheduleId;
                        item.ScheduleContent = craneOperationModel.ScheduleContent;
                    }
                }
                if (String.IsNullOrEmpty(craneOperationModel.ScheduleId) && !String.IsNullOrEmpty(craneOperationModel.ScheduleContent))
                {
                    item.ScheduleContent = craneOperationModel.ScheduleContent;
                }
            }
            await _context.SaveChangesAsync();
            return Ok(new { ret = true, data = item, code = 200 });
        }
    }
}
